var createError = require('http-errors');//http错误插件
var express = require('express'); //全局的express
var path = require('path'); //node 自带 处理路劲
var cookieParser = require('cookie-parser'); //处理cookies 编译
var logger = require('morgan');// 处理日志
// session
var session = require("express-session")
//cors
var cors = require('cors')
//app.js 项目启动的主文件


//路由模块
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');
var reactRouter = require('./routes/react');

//引入连接数据库
require('./utils/connect')

var app = express(); //获取express 所有的属性和方法

app.use(cors({ // cors 解决跨域的问题 

}))
// view engine setup
app.set('views', path.join(__dirname, 'views')); //__dirname 根目录 views重置到根目录(./views/index.js => index.js)
app.set('view engine', 'ejs'); //设置ejs为模块引擎

app.use(logger('dev')); //记录dev开发日志
app.use(express.json()); //post 提交的参数 ajax提交的post请求 req.body
app.use(express.urlencoded({ extended: false }));//表单提交的POST请求
app.use(cookieParser()); //处理cookie
app.use(express.static(path.join(__dirname, 'public'))); // public 重置到根目录  express.static 静态文件 

app.use(function(req,res,next){
  console.log("自定义中间件");
  next() //进入下一个中间件
})

// session 中间件
app.use(session({
  secret: '12345',
  name: 'test',
  cookie: {maxAge: 60 * 1000   * 60  * 2   }  ,   // 2h 
  resave: false, 
  saveUninitialized: true
}));


//配置项目的路由
// app.use('路由的父路径','路由')
app.use('/api',apiRouter);
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/react', reactRouter);

app.use(function(req,res,next){
  console.log("anan");
  next('hahahha') //进入下一个中间件
})


// catch 404 and forward to error handler
app.use(function(msg,req, res, next) {
  console.log(msg);
  
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
